package com.tulele.vtool.handler;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tulele.vtool.mapper.SysGzhMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.*;
import com.tulele.vtool.model.reqEntity.*;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.handler.MsgHandler;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;
@Slf4j
@RestController
public class UserInfoHandler {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private IUserInviteIncomeInfoService userInviteIncomeInfoService;

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    private IVipInfoService vipInfoService;

    @Autowired
    private IOrderInfoService orderInfoService;

//    @Autowired
//    private WeixinService weixinService;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

    @Autowired
    private INewLookArticleCountInfoService newLookArticleCountInfoService;

    @Autowired
    private WantedUsersService wantedUsersService;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

//    @Value("${wxShareImgPath}")
//    private String wxShareImgPath;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    @Lazy
    protected MsgHandler msgHandler;

    @Autowired
    private BDecorationArticlesService bDecorationArticlesService;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Autowired
    private IUserShareArticleInfoService userShareArticleInfoService;

    @Autowired
    private IUserPromotionSettleInfoService userPromotionSettleInfoService;

    /**
     * @param userId
     * @param userInfo ==>cardStyle 海报样式（默认0） 0-默认样式 1-样式1 2-样式2
     * @return
     */
    @PostMapping(value = "/setCardStyle", produces = "application/json;charset=UTF-8")
    public RespData setCardStyle(@RequestHeader("userId") String userId, @RequestBody(required = false) UserInfo userInfo) {

        RespData respData = new RespData();
        Integer cardStyle = userInfo.getCardStyle();

        if (cardStyle == null || cardStyle < 0 || cardStyle > 2) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        if (cardStyle == 0) {
            userInfoService.setCardStyle(Integer.parseInt(userId), cardStyle);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("设置成功");
            return respData;
        }

        int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(Integer.parseInt(userId))).orElse(0);

        if (vipStatus == 1) {
            userInfoService.setCardStyle(Integer.parseInt(userId), cardStyle);

            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("设置成功");
            return respData;
        }

        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("设置失败-您还不是会员");
        return respData;
    }

    //多锁客 赠送7天 vip
    @GetMapping(value = "/giveVip", produces = "application/json;charset=UTF-8")
    public RespData giveVip(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        if (springProfilesActive != null
                && (springProfilesActive.equals("proddsk"))) { //多锁客

            Integer finalUserId = Integer.parseInt(userId);

            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(finalUserId);
            //如果没有查到购买信息，说明是第一次购买
            if (userVipValidInfoInDB == null) {

                UserVipValidInfo vipValidInfo = new UserVipValidInfo();
                vipValidInfo.setUserId(finalUserId);
                vipValidInfo.setBeginTime(DateUtil.getCurDate());
                //DateTime endTime = new DateTime(DateUtil.getCurDate()); //20200303
                Calendar cal = Calendar.getInstance();
                cal.setTime(DateUtil.getCurDate());//设置起时间
                if(springProfilesActive.equals("proddsk")) {
                    cal.add(Calendar.DATE, 7); //7天
                }else if(springProfilesActive.equals("prodzx1") || springProfilesActive.equals("prodhyxt")) {
                    cal.add(Calendar.DATE, 30); //30天
                }

                vipValidInfo.setEndTime(cal.getTime());

                vipValidInfo.setVipLev(1);
                vipValidInfo.setVipStatus(1);
                vipValidInfo.setCreateTime(DateUtil.getCurDate());

                int r1 = vipInfoService.recordUserVipValidInfo(vipValidInfo);

                //记录购买日志
                UserVipLogInfo userVipLogInfo = new UserVipLogInfo();
                userVipLogInfo.setUserId(finalUserId);
                userVipLogInfo.setVipLev(1);
                userVipLogInfo.setCreateTime(DateUtil.getCurDate());

                int r2 = vipInfoService.recordUserVipLogInfo(userVipLogInfo);

                //修改用户vip状态
                UserInfo updateVipUser = new UserInfo();
                updateVipUser.setUserId(finalUserId);
                updateVipUser.setModifyTime(DateUtil.getCurDate());
                updateVipUser.setConcernStatus(1);//解决弹出关注的问题
                updateVipUser.setVipStatus(1);
                int r3 = userInfoService.modifyWxUserInfo(updateVipUser);
            }


        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @GetMapping(value = "/sendCoupon", produces = "application/json;charset=UTF-8")
    public RespData sendCoupon(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) throws Exception {

        Integer userIdInt = Integer.valueOf(userId);
        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);
        PlatformSysInfo platformSysInfo = sysGzhService.getPlatformSysInfo(springProfilesActive);
        String msg ="";

        Integer todayOrderCount= orderInfoService.queryTodayOrderCount(userIdInt);//获取该用户今天提交的订单数

        if (springProfilesActive != null &&  //特价号不推优惠券
                !springProfilesActive.equals("prodjzyxt") &&
                !springProfilesActive.equals("back_zkt")) {
            if(todayOrderCount>2) {
                msg = SysConstant.PUSH_CANCEL_AN_ORDER2.replace(SysConstant.frontDomain, platformSysInfo.getFrontDomain());
            }else{
                msg = SysConstant.PUSH_CANCEL_AN_ORDER.replace(SysConstant.frontDomain, platformSysInfo.getFrontDomain());
            }
        } else {
            if (todayOrderCount >2) {
                msg = SysConstant.PUSH_CANCEL_AN_ORDER_SPECIALIZED2.replace(SysConstant.frontDomain, platformSysInfo.getFrontDomain());
            } else {
                msg = SysConstant.PUSH_CANCEL_AN_ORDER_SPECIALIZED.replace(SysConstant.frontDomain, platformSysInfo.getFrontDomain());
            }
        }

        //region （公众号做通）20210902
        if(userInfo!=null && !userInfo.getGzhCode().equals(springProfilesActive)){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,userIdInt);
            if(userGroupOpenId!=null){
                userInfo.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
            msg =ToolUtil.handleMsgmenuidByIOS(msg);
        }

        //危险时间暂不崔单
        WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(userInfo.getOpenId()).content(msg).build();
        try {

            WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(springProfilesActive);
            weixinService.getKefuService().sendKefuMessage(message);

            if (todayOrderCount >2){
                msgHandler.returnKF(weixinService,userInfo.getOpenId(),platformSysInfo);
            }

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }


    @PostMapping(value = "/getUserBusinessCardInfo", produces="application/json;charset=UTF-8")
    public RespData getUserBusinessCardInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        Integer userIdInt = Integer.valueOf(userId);

        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(13);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("signature", userInfo.getSignature());
        userInfoMap.put("telNum", userInfo.getTelNum());
        userInfoMap.put("company", userInfo.getCompany());
        userInfoMap.put("qrcodeUrl", userInfo.getQrcodeUrl());
        userInfoMap.put("billUrl", userInfo.getBillUrl());
        userInfoMap.put("jobPosition", userInfo.getJobPosition());
        userInfoMap.put("jobTime", userInfo.getJobTime());
        userInfoMap.put("vipStatus", userInfo.getVipStatus());

        //获取品牌信息
        List<String> userBrandInfo = userBrandInfoService.getUserBrandNameInfo(userIdInt);
        if (CollectionUtils.isNotEmpty(userBrandInfo)) {
            userInfoMap.put("brandName", String.join(",", userBrandInfo));
        }

        //获取用户微信头像

        //region （公众号做通）20210902
        if(userInfo!=null && !userInfo.getGzhCode().equals(springProfilesActive)){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,userIdInt);
            if(userGroupOpenId!=null){
                userInfo.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion


        String openId = userInfo.getOpenId();
        if (StringUtils.isNotBlank(openId)) {
            try {
//                WeixinServiceDL weixinService= objectFactory.getObject();
//                weixinService.reSetConfigStorage(springProfilesActive);
                PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

                WxMpUser wxMpUser = weixinService.getUserService().userInfo(openId);

                if (wxMpUser != null) {
                    //userInfoMap.put("userWxAvatar", wxMpUser.getHeadImgUrl());
                    userInfoMap.put("userWxAvatar", userInfo.getAvatarUrl());//getUserService()不再返回头像和昵称
                }

            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }


        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(userInfoMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 按类型获取用户的收益
     * @param userId
     * @param getUserInviteIncomeReqBean 今天、本周、本月、全部
     * @return
     */
    @PostMapping(value = "/getUserInviteIncome", produces="application/json;charset=UTF-8")
    public RespData getUserInviteIncome(@RequestHeader("userId") String userId, @RequestBody GetUserInviteIncomeReqBean getUserInviteIncomeReqBean) {

        Integer queryType = 1;
        if (getUserInviteIncomeReqBean != null && getUserInviteIncomeReqBean.getQueryType() != null) {
            queryType = getUserInviteIncomeReqBean.getQueryType();
        }

        Map<String, Object> queryMap = Maps.newHashMapWithExpectedSize(3);
        queryMap.put("userId", userId);
        queryMap.put("queryType", queryType);

        if (queryType.intValue() == 2) {

            queryMap.put("startTime", DateUtil.getFirstDayOfWeek(DateUtil.getCurDate()));
            queryMap.put("endTime", DateUtil.getLastDayOfWeek(DateUtil.getCurDate()));

        }

        Double incomeAmount = userInviteIncomeInfoService.getUserIncomeStatis(queryMap);

        Map<String, Double> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("incomeAmount", incomeAmount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 获取用户邀请收入明细
     * @param userId 用户 ID
     * @return 用户邀请收入明细
     */
    @PostMapping(value = "/getUserInviteIncomeDetail", produces="application/json;charset=UTF-8")
    public RespData getUserInviteIncomeDetail(@RequestHeader("userId") String userId) {
        Map<String, Object> queryMap = Maps.newHashMapWithExpectedSize(3);
        queryMap.put("userId", userId);
        queryMap.put("queryType", 4);

        Double incomeAmount = userInviteIncomeInfoService.getUserIncomeStatis(queryMap);// 总收益
        List<UserInviteIncomeInfo> userInviteIncomeDetailList = userInviteIncomeInfoService.getUserInviteIncomeDetail(Integer.valueOf(userId));// 明细

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("incomeAmount", incomeAmount);
        resultMap.put("userInviteIncomeDetailList", userInviteIncomeDetailList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getUserHomeInfo", produces="application/json;charset=UTF-8")
    public RespData getUserHomeInfo(@RequestHeader("userId") String userId) throws Exception {

        //log.error("执行getUserHomeInfo 开始："+DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));
        Integer userIdInt = Integer.valueOf(userId);

        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

        //嫌疑人自动拉黑 start
        boolean r = wantedUsersService.checkAvatar(userIdInt, userInfo.getNickName());
        if (r) {
            userInfoService.setBlockState(userIdInt);
            userInfo.setBlockState(1);
        }
        //嫌疑人自动拉黑 end

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(7);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("vipStatus", Optional.ofNullable(userInfo.getVipStatus()).orElse(0));
        userInfoMap.put("accountBalance", userInfo.getAccountBalance());
        userInfoMap.put("blockState", userInfo.getBlockState());

        //获取VIP有效期
        UserVipValidInfo userVipValidInfo = vipInfoService.getVipValidInfo(userIdInt);
        if (userVipValidInfo != null) {
            userInfoMap.put("vipExpireDate", DateUtil.getFormatDate("YYYY-MM-dd", userVipValidInfo.getEndTime()));
        }


        Map<String, Object> incomeInfoMap = Maps.newHashMapWithExpectedSize(5);

        //获取当天收入统计
        Map<String, Object> curDayInomeQueryMap = Maps.newHashMapWithExpectedSize(3);
        curDayInomeQueryMap.put("userId", userId);
        curDayInomeQueryMap.put("queryType", 1);

        Double curDayInome = userInviteIncomeInfoService.getUserIncomeStatis(curDayInomeQueryMap);
        incomeInfoMap.put("curDayInome", Optional.ofNullable(curDayInome).orElse(0d));

        //获取当周收入统计
        Map<String, Object> curWeekIncomeQueryMap = Maps.newHashMapWithExpectedSize(3);
        curWeekIncomeQueryMap.put("userId", userId);
        curWeekIncomeQueryMap.put("queryType", 2);
        curWeekIncomeQueryMap.put("startTime", DateUtil.getFirstDayOfWeek(DateUtil.getCurDate()));
        curWeekIncomeQueryMap.put("endTime", DateUtil.getLastDayOfWeek(DateUtil.getCurDate()));

        Double curWeekIncome = userInviteIncomeInfoService.getUserIncomeStatis(curWeekIncomeQueryMap);
        incomeInfoMap.put("curWeekIncome", Optional.ofNullable(curWeekIncome).orElse(0d));

        //获取当月收入统计
        Map<String, Object> curMonthIncomeQueryMap = Maps.newHashMapWithExpectedSize(3);
        curMonthIncomeQueryMap.put("userId", userId);
        curMonthIncomeQueryMap.put("queryType", 3);

        Double curMonthIncome = userInviteIncomeInfoService.getUserIncomeStatis(curMonthIncomeQueryMap);
        incomeInfoMap.put("curMonthIncome", Optional.ofNullable(curMonthIncome).orElse(0d));

        //获取累计收入统计
        Map<String, Object> totalIncomeQueryMap = Maps.newHashMapWithExpectedSize(3);
        totalIncomeQueryMap.put("userId", userId);
        totalIncomeQueryMap.put("queryType", 4);

        Double totalIncome = userInviteIncomeInfoService.getUserIncomeStatis(totalIncomeQueryMap);
        incomeInfoMap.put("totalIncome", Optional.ofNullable(totalIncome).orElse(0d));

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(5);
        resultMap.put("userInfo", userInfoMap);

        //获取品牌信息
        List<String> userBrandInfo = userBrandInfoService.getUserBrandNameInfo(userIdInt);
        if (CollectionUtils.isNotEmpty(userBrandInfo)) {
            resultMap.put("brandName", String.join(",", userBrandInfo));
        }

        //邀请收入信息
        resultMap.put("inviteIncomeInfo", incomeInfoMap);

        //当前用户的userId
        resultMap.put("curUserId", userId);

        //log.error("执行getUserHomeInfo 结束："+DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getInviteUserInfo", produces="application/json;charset=UTF-8")
    public RespData getInviteUserInfo(@RequestHeader("userId") String userId, @RequestBody GetInviteUserInfoReqBean getInviteUserInfoReqBean) {

        Map<String, Object> queryMap = Maps.newHashMap();

        Integer pageNum = getInviteUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = getInviteUserInfoReqBean.getPageSize();
        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = 10;
        }

        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);
        queryMap.put("userId", Integer.valueOf(userId));

        Integer queryType = 1;
        if (getInviteUserInfoReqBean != null && getInviteUserInfoReqBean.getQueryType() != null) {
            queryType = getInviteUserInfoReqBean.getQueryType();
        }

        if (queryType.intValue() == 2) {

            queryMap.put("startTime", DateUtil.getFirstDayOfWeek(DateUtil.getCurDate()));
            queryMap.put("endTime", DateUtil.getLastDayOfWeek(DateUtil.getCurDate()));

        }

        PageInfo<CombinedInvitedVipUserInfo> combinedInvitedVipUserInfoPageInfo = userInfoService.getInvitedVipUserInfo(queryMap);

        List<CombinedInvitedVipUserInfo> invitedVipUserInfoList = combinedInvitedVipUserInfoPageInfo.getList();

        //2020025 屏蔽
//        if (CollectionUtils.isNotEmpty(invitedVipUserInfoList)) {
//            invitedVipUserInfoList.stream().parallel().forEach(info -> {
//                int vipLev = Optional.ofNullable(info.getVipLev()).orElse(1);
//                int inviteUserBonus = ToolUtil.getVipBonus(vipLev);
//                info.setInviteUserBonus(inviteUserBonus + 0d);
//            });
//        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        long count = combinedInvitedVipUserInfoPageInfo.getTotal();
        resultMap.put("count", count);
        resultMap.put("items", invitedVipUserInfoList);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/modifyUserNickName", produces="application/json;charset=UTF-8")
    public RespData modifyUserNickName(@RequestHeader("userId") String userId, @RequestBody ModifyUserNickNameReqBean modifyUserNickNameReqBean) {

        if (modifyUserNickNameReqBean == null || StringUtils.isBlank(modifyUserNickNameReqBean.getNickName())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setNickName(modifyUserNickNameReqBean.getNickName());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserNickName(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/modifyUserSignature", produces="application/json;charset=UTF-8")
    public RespData modifyUserSignature(@RequestHeader("userId") String userId, @RequestBody ModifyUserSignatureReqBean modifyUserSignatureReqBean) {

        if (modifyUserSignatureReqBean == null || StringUtils.isBlank(modifyUserSignatureReqBean.getSignature())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setSignature(modifyUserSignatureReqBean.getSignature());
        userInfo.setJobPosition(modifyUserSignatureReqBean.getJobPosition());
        userInfo.setJobTime(modifyUserSignatureReqBean.getJobTime());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserSignature(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getUserGuidance", produces="application/json;charset=UTF-8")
    public RespData getUserGuidance() {

        Map<String, String> userGuidanceInfoMap1 = Maps.newHashMapWithExpectedSize(2);
        userGuidanceInfoMap1.put("guidanceName", "如何获取品牌文章");
        userGuidanceInfoMap1.put("guidanceUrl", "https://www.baidu.com");

        Map<String, String> userGuidanceInfoMap2 = Maps.newHashMapWithExpectedSize(2);
        userGuidanceInfoMap2.put("guidanceName", "如何修改个人资料");
        userGuidanceInfoMap2.put("guidanceUrl", "https://www.163.com");

        Map<String, String> userGuidanceInfoMap3 = Maps.newHashMapWithExpectedSize(2);
        userGuidanceInfoMap3.put("guidanceName", "如何快速跟进用户");
        userGuidanceInfoMap3.put("guidanceUrl", "https://www.sohu.com");

        List<Map<String, String>> userGuidanceInfo = Lists.newArrayList();
        userGuidanceInfo.add(userGuidanceInfoMap1);
        userGuidanceInfo.add(userGuidanceInfoMap2);
        userGuidanceInfo.add(userGuidanceInfoMap3);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("userGuidanceInfo", userGuidanceInfo);
        RespData respData = new RespData();
        respData.setData(resultMap);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getLookArticleUserInfo", produces="application/json;charset=UTF-8")
    public RespData getLookArticleUserInfo(@RequestHeader("userId") String userId, @RequestBody GetLookArticleUserInfoReqBean getLookArticleUserInfoReqBean) {

        Map<String, Object> queryMap = Maps.newHashMap();

        Integer pageNum = getLookArticleUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = getLookArticleUserInfoReqBean.getPageSize();
        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = 10;
        }

        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);
        queryMap.put("userId", Integer.valueOf(userId));

        PageInfo<CombinedLookArticleUserInfo> userInfoPageInfo = userInfoService.getLookArticleUserInfo(queryMap);

        List<CombinedLookArticleUserInfo> userInfoList = userInfoPageInfo.getList();
        if (CollectionUtils.isNotEmpty(userInfoList)) {
            userInfoList.forEach(info -> {

                LookArticleInfo lookArticleInfo = new LookArticleInfo();
                lookArticleInfo.setUserId(info.getUserId());
                lookArticleInfo.setOtherUserId(Integer.valueOf(userId));
                CombinedLookArticleUserInfo lookArticleStatisInfo = lookArticleInfoService.getUserLookArticleStatisInfo(lookArticleInfo);

                if (lookArticleStatisInfo != null) {
                    info.setLookArticleCount(lookArticleStatisInfo.getLookArticleCount());
                    info.setLookCount(lookArticleStatisInfo.getLookCount());

                    NewLookArticleCountInfo queryNewLookArticleCountInfo = new NewLookArticleCountInfo();
                    queryNewLookArticleCountInfo.setUserId(info.getUserId());
                    queryNewLookArticleCountInfo.setOtherUserId(Integer.parseInt(userId));

                    NewLookArticleCountInfo newLookArticleCountInfoInDB = newLookArticleCountInfoService.getNewLookArticleInfo(queryNewLookArticleCountInfo);
                    if (newLookArticleCountInfoInDB != null && newLookArticleCountInfoInDB.getId() != null) {

                        int newLookCount = Optional.ofNullable(newLookArticleCountInfoInDB.getLookCount()).orElse(0);
                        info.setNewLookCount(newLookCount);

                    } else {

                        info.setNewLookCount(0);

                    }

                    //info.setNickName(info.getNickName().length() > 10 ? info.getNickName() + "…" : info.getNickName());

                }

            });
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        long count = userInfoPageInfo.getTotal();
        resultMap.put("count", count);
        resultMap.put("items", userInfoList);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/modifyUserQrCodeInfo", produces="application/json;charset=UTF-8")
    public RespData modifyUserQrCodeInfo(@RequestHeader("userId") String userId, @RequestBody ModifyUserQrCodeInfoReqBean modifyUserSignatureReqBean) {

        if (modifyUserSignatureReqBean == null || StringUtils.isBlank(modifyUserSignatureReqBean.getQrCodeImgUrl())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setQrcodeUrl(modifyUserSignatureReqBean.getQrCodeImgUrl());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserQrcodeUrl(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }


    @PostMapping(value = "/modifyUserBillInfo", produces="application/json;charset=UTF-8")
    public RespData modifyUserBillInfo(@RequestHeader("userId") String userId, @RequestBody ModifyUserQrCodeInfoReqBean modifyUserSignatureReqBean) {

        if (modifyUserSignatureReqBean == null || StringUtils.isBlank(modifyUserSignatureReqBean.getBillImgUrl())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setBillUrl(modifyUserSignatureReqBean.getBillImgUrl());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserBillUrl(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getTotalWithdrawAmount", produces="application/json;charset=UTF-8")
    public RespData getTotalWithdrawAmount(@RequestHeader("userId") String userId) {

        Double accountBalance = userInfoService.getUserAccountBalance(Integer.parseInt(userId));

        Map<String, Double> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("totalWithdrawAmount", Optional.ofNullable(accountBalance).orElse(0d));

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getOrderStatus", produces="application/json;charset=UTF-8")
    public RespData getOrderStatus(@RequestHeader("userId") String userId, @RequestBody GetOrderStatusReqBean getOrderStatusReqBean) {

        if (getOrderStatusReqBean == null || StringUtils.isBlank(getOrderStatusReqBean.getOrderId())) {

            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;

        }

        //根据订单ID获取订单信息
        OrderInfo orderInfo = orderInfoService.getOrderSimpleInfo(getOrderStatusReqBean.getOrderId());

        Map<String, Integer> resultMap = Maps.newHashMapWithExpectedSize(2);
        if (orderInfo != null) {
            resultMap.put("orderStatus", Optional.ofNullable(orderInfo.getTransStatus()).orElse(0));
        } else {
            resultMap.put("orderStatus", 0);
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/generateJsConfig", produces="application/json;charset=UTF-8")
    public RespData generateJsConfig(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GenerateJsConfigReqBean generateJsConfigReqBean) {

        if (generateJsConfigReqBean == null || StringUtils.isBlank(generateJsConfigReqBean.getJsUrl())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        WxJsapiSignature jsapiSignature = new WxJsapiSignature();

        PlatformSysInfo platformSysInfo = sysGzhService.getPlatformSysInfo(springProfilesActive);
//        log.error("generateJsConfigReqBean:" + generateJsConfigReqBean.getJsUrl());
//        log.error("generateJsConfigReqBean  APPID:" + platformSysInfo.getSysGzh().getGzhCode()+"_"+platformSysInfo.getSysGzh().getServerUrl()+"_"+platformSysInfo.getSysGzh().getAppId());
        try {
            //PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(springProfilesActive);
            if (weixinService == null) {
                weixinService = objectFactory.getObject();
                weixinService.reSetConfigStorage(springProfilesActive);
                WeixinServiceMap.putWeixinService(springProfilesActive, weixinService);
            }
            //log.error("generateJsConfigReqBean  springProfilesActive:" +springProfilesActive);
            if (generateJsConfigReqBean != null && generateJsConfigReqBean.getJsUrl().trim().length() > 0) {
                log.error("generateJsConfigReqBean  generateJsConfigReqBean.getJsUrl():" +generateJsConfigReqBean.getJsUrl());
                jsapiSignature = weixinService.createJsapiSignature(generateJsConfigReqBean.getJsUrl());
            }

            if(springProfilesActive.equals("prodgjhkpt")){//如果是 共建获客平台，用另一个号 授权
                String replaceGzh=WeixinServiceMap.getReplaceGzh(springProfilesActive);
                WeixinServiceDL weixinService3 = WeixinServiceMap.getWeixinService(replaceGzh);
                if (weixinService3 == null) {
                    weixinService3 = objectFactory.getObject();
                    weixinService3.reSetConfigStorage(replaceGzh);
                    WeixinServiceMap.putWeixinService(replaceGzh, weixinService3);
                }
                log.error("generateJsConfigReqBean  springProfilesActive_And_replaceGzh:" +springProfilesActive+"___"+replaceGzh);
                if (generateJsConfigReqBean != null && generateJsConfigReqBean.getJsUrl().trim().length() > 0) {
                    jsapiSignature = weixinService3.createJsapiSignature(generateJsConfigReqBean.getJsUrl());
                }
            }
        } catch (WxErrorException e) {
            log.error("generateJsConfigReqBean *** WxErrorException:" + e.getMessage());
            e.printStackTrace();
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(3);
        resultMap.put("jsConfig", jsapiSignature);

        resultMap.put("shareDomainUrl", platformSysInfo.getShareDomainUrl());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/recordUserWxNotifyMsgSetInfo", produces="application/json;charset=UTF-8")
    public RespData recordUserWxNotifyMsgSetInfo(@RequestHeader("userId") String userId, @RequestBody RecordUserWxNotifyMsgSetInfoReqBean recordUserWxNotifyMsgSetInfoReqBean) {

        if (recordUserWxNotifyMsgSetInfoReqBean == null
                //|| (recordUserWxNotifyMsgSetInfoReqBean.getNotifySwitchStatus() == null && recordUserWxNotifyMsgSetInfoReqBean.getNightDisturbStatus() == null)
                ) {

            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;

        }

        WxNotifyMsgSetInfo wxNotifyMsgSetInfo = new WxNotifyMsgSetInfo();
        wxNotifyMsgSetInfo.setUserId(Integer.parseInt(userId));

        Integer notifySwitchStatus = recordUserWxNotifyMsgSetInfoReqBean.getNotifySwitchStatus();
        Integer nightDisturbStatus = recordUserWxNotifyMsgSetInfoReqBean.getNightDisturbStatus();
        Integer firstTimeArticleAcceptStatus = recordUserWxNotifyMsgSetInfoReqBean.getFirstTimeArticleAcceptStatus();
        Integer secondTimeArticleAcceptStatus = recordUserWxNotifyMsgSetInfoReqBean.getSecondTimeArticleAcceptStatus();
        Integer thirdTimeArticleAcceptStatus = recordUserWxNotifyMsgSetInfoReqBean.getThirdTimeArticleAcceptStatus();
        Integer forthTimeArticleAcceptStatus = recordUserWxNotifyMsgSetInfoReqBean.getForthTimeArticleAcceptStatus();
        Integer dailyDataReportAcceptStatus = recordUserWxNotifyMsgSetInfoReqBean.getDailyDataReportAcceptStatus();
        Integer inviteSetStatus = recordUserWxNotifyMsgSetInfoReqBean.getInviteSetStatus();
        Integer shareSetStatus = recordUserWxNotifyMsgSetInfoReqBean.getShareSetStatus();



        if (notifySwitchStatus != null) {

            wxNotifyMsgSetInfo.setNotifySwitchStatus(notifySwitchStatus);

        }

        if (nightDisturbStatus != null) {

            wxNotifyMsgSetInfo.setNightDisturbStatus(nightDisturbStatus);

        }

        if (firstTimeArticleAcceptStatus != null) {

            wxNotifyMsgSetInfo.setFirstTimeArticleAcceptStatus(firstTimeArticleAcceptStatus);

        }

        if (secondTimeArticleAcceptStatus != null) {

            wxNotifyMsgSetInfo.setSecondTimeArticleAcceptStatus(secondTimeArticleAcceptStatus);

        }

        if (thirdTimeArticleAcceptStatus != null) {

            wxNotifyMsgSetInfo.setThirdTimeArticleAcceptStatus(thirdTimeArticleAcceptStatus);

        }

        if (forthTimeArticleAcceptStatus != null) {

            wxNotifyMsgSetInfo.setForthTimeArticleAcceptStatus(forthTimeArticleAcceptStatus);

        }

        if (dailyDataReportAcceptStatus != null) {

            wxNotifyMsgSetInfo.setDailyDataReportAcceptStatus(dailyDataReportAcceptStatus);

        }

        //20200401 添加邀请按钮设置
        if (inviteSetStatus != null) {
            wxNotifyMsgSetInfo.setInviteSetStatus(inviteSetStatus);
        }

        //20211013 添加邀请按钮设置
        if (shareSetStatus != null) {
            wxNotifyMsgSetInfo.setShareSetStatus(shareSetStatus);
        }

        userInfoService.recordUserNotifySetInfo(wxNotifyMsgSetInfo);

        WxNotifyMsgSetInfo wxNotifyMsgSetInfoInDB = userInfoService.getUserNotifySetInfo(Integer.parseInt(userId));
        if (wxNotifyMsgSetInfoInDB != null) {

            //缓存用户redis开关值
            redisCacheUtil.setCacheObject("wxUserMsgAcceptSwitch" + userId, JSON.toJSONString(wxNotifyMsgSetInfo), 2592000);

        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getUserVipInfo", produces="application/json;charset=UTF-8")
    public RespData getUserVipInfo(@RequestHeader("userId") String userId) {

        Integer userIdInt = Integer.valueOf(userId);

        Integer vipStatus = userInfoService.getUserVipStatus(userIdInt);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(5);
        resultMap.put("vipStatus", Optional.ofNullable(vipStatus).orElse(0));

        //获取VIP有效期
        UserVipValidInfo userVipValidInfo = vipInfoService.getVipValidInfo(userIdInt);
        int longTimeType = 0;

        if (userVipValidInfo != null) {
            long endTimeLong = SysConstant.END_TIME_LONG_VIP; // 大于 2050-01-01 00:00:00 视为永久会员
            if(Optional.ofNullable(userVipValidInfo.getEndTime().getTime()).orElse(0L) >= endTimeLong){
                longTimeType = 1;
            }
            Date endTime = userVipValidInfo.getEndTime();
            resultMap.put("vipExpireDate", DateUtil.getFormatDate("YYYY-MM-dd", endTime));

            //获取VIP将在多少天后到期
            int remainVipDays = DateUtil.getVipValidDays(endTime);
            resultMap.put("remainVipDays", remainVipDays);
        }
        resultMap.put("longTimeType", longTimeType);
        List<String> vipPrivilegeInfoList = Lists.newArrayList();
        vipPrivilegeInfoList.add("查看谁看了我的朋友圈文章");
        vipPrivilegeInfoList.add("添加文章不限次数");
        vipPrivilegeInfoList.add("可删除文章里的任何信息、广告");

        resultMap.put("vipPrivilegeInfo", vipPrivilegeInfoList);


        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getUserWxNotifyMsgSetInfo", produces="application/json;charset=UTF-8")
    public RespData getUserWxNotifyMsgSetInfo(@RequestHeader("userId") String userId) {

        WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userInfoService.getUserNotifySetInfo(Integer.parseInt(userId));

        Map<String, Integer> resultMap = Maps.newHashMapWithExpectedSize(2);
        if (wxNotifyMsgSetInfo == null) {
            resultMap.put("notifySwitchStatus", 1);
            resultMap.put("nightDisturbStatus", 1);

            resultMap.put("firstTimeArticleAcceptStatus", 1);
            resultMap.put("secondTimeArticleAcceptStatus", 1);
            resultMap.put("thirdTimeArticleAcceptStatus", 1);
            resultMap.put("forthTimeArticleAcceptStatus", 1);
            resultMap.put("dailyDataReportAcceptStatus", 1);

        } else {
            resultMap.put("notifySwitchStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getNotifySwitchStatus()).orElse(0));
            resultMap.put("nightDisturbStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getNightDisturbStatus()).orElse(0));

            resultMap.put("firstTimeArticleAcceptStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getFirstTimeArticleAcceptStatus()).orElse(1));
            resultMap.put("secondTimeArticleAcceptStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getSecondTimeArticleAcceptStatus()).orElse(1));
            resultMap.put("thirdTimeArticleAcceptStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getThirdTimeArticleAcceptStatus()).orElse(1));
            resultMap.put("forthTimeArticleAcceptStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getForthTimeArticleAcceptStatus()).orElse(1));
            resultMap.put("dailyDataReportAcceptStatus", Optional.ofNullable(wxNotifyMsgSetInfo.getDailyDataReportAcceptStatus()).orElse(1));

            //缓存用户redis开关值
            redisCacheUtil.setCacheObject("wxUserMsgAcceptSwitch" + userId, JSON.toJSONString(wxNotifyMsgSetInfo), 2592000);

        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 查询用户个人中心的广告和表格设置开关
     * @param userId 用户 ID
     * @return
     */
    @PostMapping(value = "/getUserArticleTailSwitchSet", produces="application/json;charset=UTF-8")
    public RespData getUserArticleTailSwitchSet(@RequestHeader("userId") String userId) {
        int advertSwitchStatus = 1;// 默认开启
        int tableSwitchStatus = 1;// 默认开启

        UserArticleTailSwitchSet userArticleTailSwitchSet = userInfoService.getUserArticleTailSwitchSet(Integer.parseInt(userId));

        Map<String, Integer> resultMap = Maps.newHashMapWithExpectedSize(2);
        if (userArticleTailSwitchSet == null) {
            // 如果不存在，新增一条记录
            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = new WxNotifyMsgSetInfo();
            wxNotifyMsgSetInfo.setUserId(Integer.parseInt(userId));
            wxNotifyMsgSetInfo.setAdvertSwitchStatus(Integer.valueOf(1));// 默认开启
            wxNotifyMsgSetInfo.setTableSwitchStatus(Integer.valueOf(1));// 默认开启
            userInfoService.recordUserNotifySetInfo(wxNotifyMsgSetInfo);
        } else {
            advertSwitchStatus = Optional.ofNullable(userArticleTailSwitchSet.getAdvertSwitchStatus()).orElse(1);
            tableSwitchStatus = Optional.ofNullable(userArticleTailSwitchSet.getTableSwitchStatus()).orElse(1);
        }

        // 如果用户是非会员且表单按钮没有关闭，则关闭表单按钮
        /*Integer userVipStatus = userInfoService.getUserVipStatus(Integer.valueOf(userId));
        Integer tableSwitchStatus = userArticleTailSwitchSet.getTableSwitchStatus();
        if (userVipStatus != null && userVipStatus.intValue() == 0 && tableSwitchStatus != null && tableSwitchStatus.intValue() == 1) {
            tableSwitchStatus = Integer.valueOf(0);

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = new WxNotifyMsgSetInfo();
            wxNotifyMsgSetInfo.setId(userArticleTailSwitchSet.getId());
            wxNotifyMsgSetInfo.setTableSwitchStatus(tableSwitchStatus);
            wxNotifyMsgSetInfo.setModifyTime(DateUtil.getCurDate());

            userInfoService.updateUserNotifySetInfo(wxNotifyMsgSetInfo);
        }*/

        resultMap.put("advertSwitchStatus", advertSwitchStatus);
//        resultMap.put("tableSwitchStatus", Optional.ofNullable(tableSwitchStatus).orElse(0));
        resultMap.put("tableSwitchStatus", tableSwitchStatus);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 修改用户个人中心的广告和表格设置开关
     * @param userId 用户 ID
     * @param userArticleTailSwitchSet 开关信息
     * @return 操作结果
     */
    @PostMapping(value = "/updateUserArticleTailSwitchSet", produces="application/json;charset=UTF-8")
    public RespData updateUserArticleTailSwitchSet(@RequestHeader("userId") String userId, @RequestBody UserArticleTailSwitchSet userArticleTailSwitchSet) {
        if (Objects.isNull(userArticleTailSwitchSet)) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        userInfoService.updateUserArticleTailSwitchSet(Integer.parseInt(userId), userArticleTailSwitchSet);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/modifyUserTelNum", produces="application/json;charset=UTF-8")
    public RespData modifyUserTelNum(@RequestHeader("userId") String userId, @RequestBody ModifyUserTelNumReqBean modifyUserNickNameReqBean) {

        if (modifyUserNickNameReqBean == null || StringUtils.isBlank(modifyUserNickNameReqBean.getTelNum())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setTelNum(modifyUserNickNameReqBean.getTelNum());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserTelNum(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 修改用户职务
     * @param userId
     * @param modifyUserJobPositionReqBean
     * @return
     */
    @PostMapping(value = "/modifyUserJobPosition", produces="application/json;charset=UTF-8")
    public RespData modifyUserJobPosition(@RequestHeader("userId") String userId, @RequestBody ModifyUserJobPositionReqBean modifyUserJobPositionReqBean) {

        if (modifyUserJobPositionReqBean == null || StringUtils.isBlank(modifyUserJobPositionReqBean.getJobPosition())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setJobPosition(modifyUserJobPositionReqBean.getJobPosition());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserJobPosition(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 修改用户公司
     * @param userId
     * @param modifyUserJobCompanyReqBean
     * @return
     */
    @PostMapping(value = "/modifyUserCompany", produces="application/json;charset=UTF-8")
    public RespData modifyUserCompany(@RequestHeader("userId") String userId, @RequestBody ModifyUserJobCompanyReqBean modifyUserJobCompanyReqBean) {

        if (modifyUserJobCompanyReqBean == null || StringUtils.isBlank(modifyUserJobCompanyReqBean.getCompany())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setCompany(modifyUserJobCompanyReqBean.getCompany());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserCompany(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/generateInviteUserPoster", produces="application/json;charset=UTF-8")
    public RespData generateInviteUserPoster(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        UserInfo userInfo = userInfoService.getUserBaseInfo(Integer.parseInt(userId));

        try
        {
//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(springProfilesActive);
            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
            WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(userId, 2592000);
            File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);

            //下载用户头像
            String avatarName = UUID.randomUUID().toString() + ".jpg";
            ToolUtil.downloadAvatarPic(userInfo.getAvatarUrl(), userInfo.getUserId(), avatarName);

            String avatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH + userInfo.getUserId() + "/" + avatarName;

            String qrCodePath = qrCodePictureFile.getAbsolutePath();

            String validTime = "二维码有效期至" + DateUtil.getFormatDate("yyyy年MM月dd日", DateUtil.getCurDate());

            PlatformSysInfo platformSysInfo= sysGzhService.getPlatformSysInfo(springProfilesActive);

            File resultImg = SharedImageUtils.generateSharedImage(avatarPath, qrCodePath, userInfo.getNickName(), validTime,platformSysInfo.getWxShareImgPath(), platformSysInfoConfig.getSysGzh().getGzhCode());

            WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, resultImg);

            String mediaId = wxMediaUploadResult.getMediaId();

            //region （公众号做通）20210902
            if(userInfo!=null && !userInfo.getGzhCode().equals(springProfilesActive)){
                UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,Integer.parseInt(userId));
                if(userGroupOpenId!=null){
                    userInfo.setOpenId(userGroupOpenId.getOpenId());
                }
            }
            //endregion

            WxMpKefuMessage wxMpKefuMessage = WxMpKefuMessage.IMAGE().mediaId(mediaId).toUser(userInfo.getOpenId()).build();
            boolean result = weixinService.getKefuService().sendKefuMessage(wxMpKefuMessage);

            if (result) {

                RespData respData = new RespData();
                respData.setCode(ReturnCode.NORMAL_SUCC);
                respData.setMsg("成功");
                return respData;

            }

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        RespData respData = new RespData();
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("发送失败，请稍后再试");
        return respData;


    }

    @PostMapping(value = "/generatePublicNumQrCode", produces="application/json;charset=UTF-8")
    public RespData generatePublicNumQrCode(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GeneratePublicNumQrCodeReqBean generatePublicNumQrCodeReqBean) {

        if (generatePublicNumQrCodeReqBean == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        try {

            PlatformSysInfo platformSysInfo = sysGzhService.getPlatformSysInfo(springProfilesActive);

            //生成公众号二维码的类型 1-文章详情页生成 2-打卡页面生成
            int generateType = Optional.ofNullable(generatePublicNumQrCodeReqBean.getGenerateType()).orElse(1);

            int finalUserId = Integer.parseInt(userId);

            if (generateType == 1) {

                int articleId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getArticleId()).orElse(0);

                int articleUserId = Optional.ofNullable(articleInfoService.getArticleUserInfo(articleId)).orElse(0);

                if (articleUserId == 0) {

                    String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                    if (StringUtils.isNotBlank(shareUserId)) {

                        articleUserId = Integer.parseInt(shareUserId);

                    }

                }

                finalUserId = articleUserId;

            } else if (generateType == 2) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            }
            // 20200515 yl start
            else if (generateType == 3) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            }

            // 20200521 yl end

            else if (generateType == 4) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            }

            // 20200624 hyl end

            else if (generateType == 5) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            }

            // 20200521 yl end

            // 20200710 hyl end

            else if (generateType == 6) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            } else if (generateType == 7) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            } else if (generateType == 8) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }

            }

            // 20200710 yl end

            // 20201013 ljt start
            else if (generateType == 9) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }
            }
            // 20201013 ljt end

            // 20201208 ljt start 商学院未关注
            else if (generateType == 10) {

                String shareUserId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getShareUserId()).orElse("");
                if (StringUtils.isNotBlank(shareUserId)) {

                    finalUserId = Integer.parseInt(shareUserId);

                }
            }
            // 20201208 ljt end 商学院未关注

            if (finalUserId == 0) {
                finalUserId = Integer.parseInt(userId);
            }

            String targetGzhCode = springProfilesActive;//引流的目标公众号

            if (generateType != 9 && generateType != 10) {//不是 装修作品、商学院 才走引流,20201214 hyl


                if (platformSysInfo.getSysGzh().getIsDrainage() != null && platformSysInfo.getSysGzh().getIsDrainage().equals(1)) { //这个等于1 才导流
                    ArticleInfo articleInfo = articleInfoService.getArticleDetailInfo(generatePublicNumQrCodeReqBean.getArticleId());
                    if (articleInfo != null && articleInfo.getArticleBrandId() != null) {
                        GzhBrandMap gzhBrandMap = sysGzhService.getGzhBrandMap(articleInfo.getArticleBrandId());

                        if (gzhBrandMap != null) {
                            targetGzhCode = gzhBrandMap.getGzhCode();
                        }

                        if (springProfilesActive.equals("proddsk") ||    //多锁客
                                springProfilesActive.equals("prodgjhkpt") ||    //共建获客平台
                                springProfilesActive.equals("prodhksch") ||//获客素材号
                                springProfilesActive.equals("prodjpsj") ||    //电商获客爆文
                                springProfilesActive.equals("prodjzyxt") ||    //金钻云学堂
                                springProfilesActive.equals("prodkdhe") ||//开单获客
                                springProfilesActive.equals("prodkdxsq") ||    //开单小神器
                                springProfilesActive.equals("prodkhzzzs") ||    //客户追踪助手
                                springProfilesActive.equals("prodkshf") ||//抗衰护肤学堂
                                springProfilesActive.equals("prodmyds") ||    //美牙大使
                                springProfilesActive.equals("prodssxt") ||    //塑身学堂
                                springProfilesActive.equals("prodyysck") ||    //获客素材库
                                springProfilesActive.equals("prodyyzs")) {    //获客掌柜
                            targetGzhCode = springProfilesActive;  //第三方合作号 默认不导流
                        }

                        Integer[] tarBrandIds = new Integer[]{35907, 37595, 38924, 39690, 45451};
                        if (springProfilesActive.equals("prodyyzs") && Arrays.asList(tarBrandIds).contains(articleInfo.getArticleBrandId())) {// 20210803 获客掌柜 对应品牌导去 客户追踪助手
                            targetGzhCode = "prodkhzzzs";//客户追踪助手
                        }

                        if (springProfilesActive.equals("prodshsck")) { //私护素材库
                            if (targetGzhCode.equals("prodshjj")) {//如果当前号是私护素材库，目标号是 私护之家，就留在 素材库
                                targetGzhCode = "prodshsck";//私护素材库
                            }
                        }

                        if (articleInfo.getArticleBrandId().equals(36552) && //完美医生
                                (springProfilesActive.equals("prodyyzs") || springProfilesActive.equals("prodkhzzzs"))) {//客户追踪助手 和 获客掌柜 的 完美医生 都去 美牙大使  20211109
                            targetGzhCode = "prodmyds";//美牙大使
                        }

                        Integer[] yysckTarBrandIds = new Integer[]{45763,50495};//琼滋女王 纯拾光
                        if (springProfilesActive.equals("prodyysck") && Arrays.asList(yysckTarBrandIds).contains(articleInfo.getArticleBrandId())) {// 20211223 获客素材库 对应品牌导去 抗衰护肤学堂
                            targetGzhCode = "prodkshf";//抗衰护肤学堂
                        }
                    }
                }
            }

//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(targetGzhCode);//根据文章的品牌 获取对应的 公众号，实现引流
            //PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(targetGzhCode);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());

            WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(targetGzhCode);
            if (weixinService == null) {
                weixinService = objectFactory.getObject();
                weixinService.reSetConfigStorage(targetGzhCode);
                WeixinServiceMap.putWeixinService(targetGzhCode, weixinService);
            }

            //20200716 二维码参数中添加参数 文章分配人ID_文章ID_当前用户ID
            WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(String.valueOf(finalUserId) + "_" + generatePublicNumQrCodeReqBean.getArticleId() + "_" + userId, 2592000);
            File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);


            String imgName = UUID.randomUUID().toString() + ".jpg";

            AliImgUtil.uploadWechatQrCodeImg(userId, imgName, qrCodePictureFile);

            String qrCodeUrl = SysConstant.USER_PARAM_QRCODE_IMG_ACCESS_PREFIX + SysConstant.WX_PN_QRCODE_IMG_FOLDER_PATH + userId + "/" + imgName;

            Map<String, String> resultMap = Maps.newHashMapWithExpectedSize(2);
            resultMap.put("qrCodeUrl", qrCodeUrl);

            //用来给用户推送关注公众号之前想要保存的文章
            int articleId = Optional.ofNullable(generatePublicNumQrCodeReqBean.getArticleId()).orElse(0);

            int articleType = Optional.ofNullable(generatePublicNumQrCodeReqBean.getArticleType()).orElse(2);

            if (articleId > 0 && articleType == 1) {
                redisCacheUtil.setCacheObject(userId + "articleIdBeforeSubscribe", articleId, 3600);
            } else {
                redisCacheUtil.removeSingleCache(userId + "articleIdBeforeSubscribe");
            }

            // 20210721 hyl 早晚安 生成关注二维码
            if (2 == generateType) {
                redisCacheUtil.setCacheObject("PUNCH_CLOCK" + userId, DateUtil.getCurDate(), 3600);
            }

            // 20200515 yl start
            if (3 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_THREE" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200515 yl end

            // 20200521 yl start
            if (4 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_FOUR" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200521 yl end

            // 20200521 yl start
            if (5 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_FIVE" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200521 yl end

            // 20200521 yl start
            if (6 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_SIX" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200521 yl end

            // 20200521 yl start
            if (7 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_SEVEN" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200521 yl end

            // 20200825 hyl start
            if (8 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_EIGHT" + userId, DateUtil.getCurDate(), 3600);
            }
            // 20200825 hyl end

            // 20201013 ljt start
            if (9 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_NINE" + userId, articleId, 3600);
            }
            // 20201013 ljt end

            // 20201208 ljt start 商学院未关注
            if (10 == generateType) {
                redisCacheUtil.setCacheObject("STATUS_IS_TEN" + userId, articleId, 3600);//articleId是商学院课程ID
            }
            // 20201208 ljt end 商学院未关注


            RespData respData = new RespData();
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setData(resultMap);
            respData.setMsg("成功");
            return respData;


        } catch (WxErrorException e) {
            e.printStackTrace();
        }


        RespData respData = new RespData();
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("获取二维码失败，请稍后再试");
        return respData;
    }

    /**
     * 分页获取邀请的用户信息
     * @param userId
     * @param getRecommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/getInvitedUserInfo", produces="application/json;charset=UTF-8")
    public RespData getInvitedUserInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean getRecommendUserInfoReqBean) {

        Integer pageNum = getRecommendUserInfoReqBean.getPageNum();
        if (pageNum == null) {
            pageNum = 1;
        }

        Integer pagSize = getRecommendUserInfoReqBean.getPageSize();
        if (pagSize == null) {
            pagSize = 10;
        }

        Integer lookUserId = Integer.parseInt(userId);

        if (getRecommendUserInfoReqBean.getLookUserId() != null && getRecommendUserInfoReqBean.getLookUserId() > 0) {
            lookUserId = getRecommendUserInfoReqBean.getLookUserId();
        }

        //获取分页信息
//        PageInfo<UserInfo> invitedUserInfoPageInfo = null;
//
//        if(springProfilesActive.equals("prodgjhkpt") || springProfilesActive.equals("back_zkt")) {//共建获客平台
//            invitedUserInfoPageInfo= userInfoService.getInvitedUserInfoPage_gjhkpt(Integer.parseInt(userId), pageNum, pagSize);
//        }else {
//            invitedUserInfoPageInfo = userInfoService.getInvitedUserInfo(Integer.parseInt(userId), pageNum, pagSize);
//        }
//        log.error("*****lookUserId:"+lookUserId);

        List<UserInfo> invitedUserList = null;
        if (springProfilesActive.equals("prodgjhkpt") || springProfilesActive.equals("back_zkt")) {//共建获客平台
            invitedUserList = userInfoService.getInvitedUserInfo_gjhkpt(lookUserId);
        } else {
//            invitedUserList = userInfoService.getInvitedUserInfo(lookUserId);
            invitedUserList = userInfoService.getInvitedUserInfobyPage(lookUserId, pageNum, pagSize);
        }

        //long count = invitedUserInfoPageInfo.getTotal();
        //long count = 0;

        Map<String, Object> infoMap = Maps.newHashMapWithExpectedSize(3);

        //List<UserInfo> userInfos = invitedUserList;
        if (CollectionUtils.isNotEmpty(invitedUserList)) {

            //count = invitedUserList.size();

            invitedUserList.forEach(info -> {

                Date createTime = info.getCreateTime();
                if (createTime != null) {
//                    String regTime = DateUtil.getFormatDate("yyyy年MM月dd日 HH时mm分", createTime);
                    String regTime = DateUtil.getFormatDate("yyyy/MM/dd", createTime);
                    info.setRegTime(regTime);
                }
            });
        }

        Integer count = userInfoService.getInvitedRegUserCount(lookUserId);

        infoMap.put("count", count);

        infoMap.put("items", invitedUserList);

//        log.error("*****count:"+count);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(infoMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/getUserSetPageInfo", produces="application/json;charset=UTF-8")
    public RespData getUserSetPageInfo(@RequestHeader("userId") String userId) {

        Integer userIdInt = Integer.valueOf(userId);

        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(7);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("vipStatus", Optional.ofNullable(userInfo.getVipStatus()).orElse(0));
        userInfoMap.put("accountBalance", userInfo.getAccountBalance());

        //获取VIP有效期
        UserVipValidInfo userVipValidInfo = vipInfoService.getVipValidInfo(userIdInt);
        int longTimeType = 0;
        if (userVipValidInfo != null) {
            long endTimeLong = SysConstant.END_TIME_LONG_VIP; // 大于 2050-01-01 00:00:00 视为永久会员
            if(Optional.ofNullable(userVipValidInfo.getEndTime().getTime()).orElse(0L) >= endTimeLong){
                longTimeType = 1;
            }
            userInfoMap.put("vipExpireDate", DateUtil.getFormatDate("YYYY-MM-dd", userVipValidInfo.getEndTime()));
        }
        userInfoMap.put("longTimeType", longTimeType);
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(12);
        resultMap.put("userInfo", userInfoMap);

        //获取品牌信息
        List<String> userBrandInfo = userBrandInfoService.getUserBrandNameInfo(userIdInt);
        if (CollectionUtils.isNotEmpty(userBrandInfo)) {
            resultMap.put("brandName", String.join(",", userBrandInfo));
        }

        //当前用户的userId
        resultMap.put("curUserId", userId);

        //获取推荐注册的用户信息
        int invitedRegUserCount = userInfoService.getInvitedRegUserCount(userIdInt);
        resultMap.put("invitedRegUserCount", invitedRegUserCount);

        //查询用户有效的通知频率设置开关
        int validNotifySetStatus = Optional.ofNullable(userInfoService.getUserValidNotifySetStatus(userIdInt)).orElse(1);
        resultMap.put("validNotifySetStatus", validNotifySetStatus);

        UserInfo userSubTimeRelationInfo = userInfoService.getUserSubTimeRelationInfo(Integer.parseInt(userId));
        if (userSubTimeRelationInfo != null) {

            Date subscriberTime = userSubTimeRelationInfo.getSubscribeTime();

            int couponRemainTime = 0;

            int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(Integer.parseInt(userId))).orElse(0);

            if (subscriberTime != null && vipStatus == 0) {

                //优惠券剩余有效时间
                couponRemainTime = SysConstant.COUPON_VALID_TIME - DateUtil.getTimeDiff(3, subscriberTime);
                if (couponRemainTime < 0 || couponRemainTime > 26) {
                    couponRemainTime = 0;
                }

                if (couponRemainTime == 0) {

                    resultMap.put("couponStatus", 0);
                    resultMap.put("couponRemainTime", 0);
                    resultMap.put("couponAmount", 0);

                } else {

                    resultMap.put("couponStatus", 1);
                    resultMap.put("couponRemainTime", couponRemainTime);
                    resultMap.put("couponAmount", SysConstant.COUPON_AMOUNT);

                }

            } else {

                resultMap.put("couponStatus", 0);
                resultMap.put("couponRemainTime", couponRemainTime);
                resultMap.put("couponAmount", 0);

            }


        }

        //获取推荐人信息
        int referrer = Optional.ofNullable(userInfoService.getUserReferer(userIdInt)).orElse(0);
        if (referrer > 0) {

            UserInfo referrerInfo = userInfoService.getUserBaseInfo(referrer);
            if (referrerInfo != null) {

                Map<String, Object> referrerInfoMap = Maps.newHashMapWithExpectedSize(3);
                referrerInfoMap.put("referrerNickName", referrerInfo.getNickName());
                referrerInfoMap.put("referrerAvatarUrl", referrerInfo.getAvatarUrl());

                resultMap.put("referrerInfo", referrerInfoMap);

            }

        }

        //先查询是否是否关注了公众号
        int userConcernStatus = Optional.ofNullable(userInfoService.getUserConcernStatus(Integer.valueOf(userId))).orElse(0);
        resultMap.put("concernStatus", userConcernStatus);

        //20200401 添加邀请按钮设置
        WxNotifyMsgSetInfo userNotifyMsgSetInfo= userInfoService.getUserNotifySetInfo(userIdInt);
        if(userNotifyMsgSetInfo!=null){
            resultMap.put("inviteSetStatus", userNotifyMsgSetInfo.getInviteSetStatus());
            resultMap.put("shareSetStatus", userNotifyMsgSetInfo.getShareSetStatus());
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getCustomerPageMarqueeInfo", produces="application/json;charset=UTF-8")
    public RespData getUserWithdrawMarqueeInfo(@RequestHeader("userId") String userId) {

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        List<CustomerMarqueeInfo> marqueeInfo = Lists.newArrayList();

        List<LookUserArticleStatisInfo> lookUserArticleStatisInfos = lookArticleInfoService.getLookUserArticleStatisInfo(Integer.parseInt(userId), 5);

        if (CollectionUtils.isNotEmpty(lookUserArticleStatisInfos) && lookUserArticleStatisInfos.size() > 0) {

            lookUserArticleStatisInfos.forEach(info -> {

                if (info != null) {

                    int totalLookCount = Optional.ofNullable(info.getTotalLookCount()).orElse(1);
                    Integer lookUserId = info.getUserId();

                    UserInfo lookUserInfo = userInfoService.getUserBaseInfo(lookUserId);
                    if (lookUserInfo != null) {
                        CustomerMarqueeInfo customerMarqueeInfo = new CustomerMarqueeInfo();
                        customerMarqueeInfo.setAvatarUrl(lookUserInfo.getAvatarUrl());
                        customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 已获客 " + totalLookCount + " 次");

                        marqueeInfo.add(customerMarqueeInfo);
                    }

                }
            });

            int lookUserArticleStatisInfoSize = lookUserArticleStatisInfos.size();
            if (lookUserArticleStatisInfoSize == 0) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(5));
            } else if (lookUserArticleStatisInfoSize == 1) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(4));
            } else if (lookUserArticleStatisInfoSize == 2) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(3));
            } else if (lookUserArticleStatisInfoSize == 3) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(2));
            } else if (lookUserArticleStatisInfoSize == 4) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(1));
            }

        } else {

            marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(5));

        }

        resultMap.put("marqueeInfo", marqueeInfo);

        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/generateUserPromotionQrCode", produces="application/json;charset=UTF-8")
    public RespData generateUserPromotionQrCode(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        String qrCodeImgUrl = null;

        Map<String, String> resultMap = Maps.newHashMap();

        try {
//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(springProfilesActive);

            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateLastTicket(userId);
            File qrCodeImgFile = weixinService.getQrcodeService().qrCodePicture(ticket);

            String fileName = UUID.randomUUID().toString() + ".png";

            String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
            String dirName = SysConstant.USER_LONG_TERM_QR_CODE_IMG_OSS_DIR + userId + "/" + formatDate + "/";

            AliyunOssClientUtil.uploadFileByLocalFile(qrCodeImgFile, dirName + fileName);

            qrCodeImgUrl = SysConstant.USER_LONG_TERM_QR_CODE_ACCESS_PREFIX + dirName + fileName;

            resultMap.put("userLongTermQrCodeImgUrl", qrCodeImgUrl);

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/modifyUserAvatar", produces="application/json;charset=UTF-8")
    public RespData modifyUserAvatar(@RequestHeader("userId") String userId, @RequestBody ModifyUserAvatarReqBean modifyUserAvatarReqBean) {

        if (modifyUserAvatarReqBean == null || StringUtils.isBlank(modifyUserAvatarReqBean.getAvatarUrl())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.valueOf(userId));
        userInfo.setAvatarUrl(modifyUserAvatarReqBean.getAvatarUrl());
        userInfo.setModifyTime(DateUtil.getCurDate());
        userInfoService.modifyUserAvatar(userInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**20200429 yl
     * 删除海报
     * @param userId
     * @return
     */
    @PostMapping(value ="deleteUserBillByUserId", produces="application/json;charset=UTF-8")
    public RespData deleteUserBillByUserId(@RequestHeader("userId") String userId){
       if (!this.userInfoService.updateUserBillByUserId(Integer.parseInt(userId))){
           RespData respData = new RespData();
           respData.setCode(ReturnCode.CLIENT_ERROR);
           respData.setMsg("参数异常");
           return respData;
       }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }
    /**20200429 yl
     * 删除二维码
     * @param userId
     * @return
     */
    @PostMapping(value = "deleteUserQrCodeByUserId", produces="application/json;charset=UTF-8")
    public RespData deleteUserQrCodeByUserId(@RequestHeader("userId") String userId){
        if (!this.userInfoService.updateUserQrCodeByUserId(Integer.parseInt(userId))){
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 20200520 yl
     * 查询用户主要信息
     * @param userId
     * @return
     */
    @PostMapping(value = "/getUserMainInfo", produces="application/json;charset=UTF-8")
    public RespData getUserMainInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody(required = false) UserInfo requestUserInfo) throws Exception {
        HashMap<String , UserInfo> map = Maps.newHashMap();
        RespData respData = new RespData();
        UserInfo userInfo = userInfoService.getUserMainInfo(Integer.valueOf(userId));
        map.put("atPresentUser",userInfo);
        if (null != requestUserInfo) {
            UserInfo userMainInfo = userInfoService.getUserMainInfo(requestUserInfo.getUserId());

            if (null != requestUserInfo.getUserId() && !Integer.valueOf(userId).equals(requestUserInfo.getUserId())) {

                //region （公众号做通）20210902
                if(userMainInfo!=null && !userMainInfo.getGzhCode().equals(springProfilesActive)){
                    UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,requestUserInfo.getUserId());
                    if(userGroupOpenId!=null){
                        userMainInfo.setOpenId(userGroupOpenId.getOpenId());
                    }
                }
                //endregion

                StringBuffer wxPushMsg = new StringBuffer();
                wxPushMsg.append("有人看了你的招商主页\n\n");
                wxPushMsg.append("\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=意向客户&msgmenuid=+++\">查看客户</a>\n\n");
                String kefuMsg = wxPushMsg.toString();

                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }

                WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(userMainInfo.getOpenId()).content(kefuMsg).build();
                try {

//                    WeixinServiceDL weixinService= objectFactory.getObject();
//                    weixinService.reSetConfigStorage(springProfilesActive);
                    PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                    //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
                    WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
                    weixinService.getKefuService().sendKefuMessage(message);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }
                // 查看信息记录
//                ArticleInfo articleInfo = articleInfoService.getArticleDetailInfo(1866675);
//                if (articleInfo == null || articleInfo.getId() == null) {
//                    respData.setCode(ReturnCode.ARTICLE_NOT_EXIST);
//                    respData.setMsg("该文章不存在");
//                    return respData;
//
//                }

                ArticleInfo articleInfo = new ArticleInfo();
                articleInfo.setId(1866675);
                articleInfo.setArticleTitle("招商主页");

                LookArticleInfo lookArticleInfo = new LookArticleInfo();
                lookArticleInfo.setUserId(Integer.valueOf(userId));
                lookArticleInfo.setOtherUserId(requestUserInfo.getUserId());
                lookArticleInfo.setArticleId(articleInfo.getId());

                //UserInfo lookUserInfo = userInfoService.getUserMainInfo(Integer.valueOf(userId));

                articleInfoService.lookOtherUserArticle(lookArticleInfo, articleInfo, requestUserInfo.getNickName(), "2",springProfilesActive);
            }

            map.put("user", userMainInfo);
        }

        if (null != userInfo){
            respData.setData(map);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;
        }
        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("参数异常");
        return respData;
    }

    /**
     * 20201013 ljt
     * 查询用户主要信息
     * @param userId
     * @return
     */
    @PostMapping(value = "/getUserFitment", produces="application/json;charset=UTF-8")
    public RespData getUserFitment(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody(required = false) UserInfo requestUserInfo) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        RespData respData = new RespData();
        UserInfo userInfo = userInfoService.getUserBaseInfo(Integer.valueOf(userId));
        resultMap.put("atPresentUser",userInfo);
        if (null != requestUserInfo) {
            PlatformSysInfo platformSysInfo= sysGzhService.getPlatformSysInfo(springProfilesActive);
            UserInfo userMainInfo = userInfoService.getUserMainInfo(requestUserInfo.getUserId());
            resultMap.put("user", userMainInfo);

            if (null != requestUserInfo.getUserId() && !Integer.valueOf(userId).equals(requestUserInfo.getUserId()) && requestUserInfo.getIntroductionId() != null) {

                String headLine = "";
                if(requestUserInfo.getIntroductionId() != null){
                    headLine = bDecorationArticlesService.queryById(requestUserInfo.getIntroductionId()).getHeadLine();
                }

                String kefuMsg = String.format(SysConstant.NEW_USER_LOOK_COMPOSITION_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfo.getFrontDomain()), headLine);

                int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(requestUserInfo.getUserId())).orElse(0);
                if (vipStatus == 1) {
                    kefuMsg = String.format(SysConstant.NEW_USER_LOOK_COMPOSITION_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfo.getFrontDomain()), userInfo.getNickName(), headLine);
                }

                //region （公众号做通）20210902
                if(userMainInfo!=null && !userMainInfo.getGzhCode().equals(springProfilesActive)){
                    UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,requestUserInfo.getUserId());
                    if(userGroupOpenId!=null){
                        userMainInfo.setOpenId(userGroupOpenId.getOpenId());
                    }
                }
                //endregion

                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }

                WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(userMainInfo.getOpenId()).content(kefuMsg).build();
                try {
                    PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                    WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

                    weixinService.getKefuService().sendKefuMessage(message);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }

                ArticleInfo articleInfo = new ArticleInfo();
                articleInfo.setId(requestUserInfo.getIntroductionId());//作品案例ID
                articleInfo.setArticleTitle("设计案例");

                LookArticleInfo lookArticleInfo = new LookArticleInfo();
                lookArticleInfo.setUserId(Integer.valueOf(userId));
                lookArticleInfo.setOtherUserId(requestUserInfo.getUserId());
                lookArticleInfo.setArticleId(requestUserInfo.getIntroductionId());

                //UserInfo lookUserInfo = userInfoService.getUserMainInfo(Integer.valueOf(userId));

                articleInfoService.lookOtherUserArticle(lookArticleInfo, articleInfo, requestUserInfo.getNickName(), "3",springProfilesActive);
            }

        }

        if (null != userInfo){
            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;
        }
        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("参数异常");
        return respData;
    }

    /**
     * 查询用户地址 yl 20200608
     * @param userId
     * @return
     */
    @PostMapping(value = "/selectRegionByUserId", produces = "application/json;charset=UTF-8")
    public RespData selectRegionByUserId(@RequestHeader("userId") String userId) {
        RespData respData = new RespData();
        respData.setData(this.userInfoService.selectRegionByUserId(Integer.valueOf(userId)));
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }
    /**
     * 用户添加地址 yl 20200608
     * @param userId
     * @return
     */
    @PostMapping(value = "/addRegionByUserId", produces = "application/json;charset=UTF-8")
    public RespData addRegionByUserId(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive,@RequestBody UserRegionInfo userRegionInfo) {
        this.userInfoService.addRegionByUserId(Integer.valueOf(userId),userRegionInfo,springProfilesActive);
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }


    @PostMapping(value = "/waterAvatar", produces = "application/json;charset=UTF-8")
    public RespData avatar(@RequestHeader("userId") String userId,@RequestBody MultipartFile file) throws Exception {
        System.out.println("开始添加水印！");
        if (!file.isEmpty()) {
            this.userInfoService.selectCountRegionByUserId(Integer.valueOf(userId));

            // 获取类所在项目路径，获取方式有多种
            //String address = SharedImageUtils.class.getResource("/").getPath() + "/static/";
            String address = "G:/123/";

            // 头像
            String avastar = address + "img/avastar.jpg";
//        String avastar = "http://zktfile.wxslzf.com/ps/20200805/image1241340.png?x-oss-process=image/resize,m_fill,w_335,h_300";
            // 二维码
            String qrcode = address + "img/qrcode.jpg";
            // 背景图片
            String background = address + "img/background.jpg";
            // 目标路径
            String result = "G:/123/result/" + UUID.randomUUID().toString();

            // 1. 通过背景图片构建 BufferedImage
            BufferedImage zoomPicture = ImageIO.read(new File(background));
            // 2. 头像裁剪成圆形
            BufferedImage roundedImage = SharedImageUtils.createRoundedImage(avastar, SharedImageUtils.AVATAR_SIZE);
            // 3. 合并头像，昵称
            BufferedImage mergeImage = SharedImageUtils.mergePicture(zoomPicture, roundedImage, "杵臼大魔王", "二维码有效期至2019年05月12日");
            // 4. 合并二维码
            mergeImage = SharedImageUtils.mergeQrcode(mergeImage, qrcode);
            // 5. 生成分享图
            ImageIO.write(mergeImage, "jpg", new File(result + ".jpg"));

            System.out.println("水印添加成功！，测试目标是：" + result + ".jpg");

            RespData respData = new RespData();
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("上传图片异常，请联系管理员");
        return respData;
    }

    @PostMapping(value = "/getUserByUserId", produces="application/json;charset=UTF-8")
    public RespData getUserByUserId(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody UserRegionInfo userRegionInfo) {

        Integer userIdInt = userRegionInfo.getUserId();

        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(9);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("signature", userInfo.getSignature());
        userInfoMap.put("telNum", userInfo.getTelNum());
        userInfoMap.put("qrcodeUrl", userInfo.getQrcodeUrl());
        userInfoMap.put("billUrl", userInfo.getBillUrl());
        userInfoMap.put("jobPosition", userInfo.getJobPosition());
        userInfoMap.put("jobTime", userInfo.getJobTime());

        //获取品牌信息
        List<String> userBrandInfo = userBrandInfoService.getUserBrandNameInfo(userIdInt);
        if (CollectionUtils.isNotEmpty(userBrandInfo)) {
            userInfoMap.put("brandName", String.join(",", userBrandInfo));
        }

        //获取用户微信头像

        //region （公众号做通）20210902
        if(userInfo!=null && !userInfo.getGzhCode().equals(springProfilesActive)){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,userIdInt);
            if(userGroupOpenId!=null){
                userInfo.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        String openId = userInfo.getOpenId();
        if (StringUtils.isNotBlank(openId)) {
            try {
                PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
                if(weixinService==null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(springProfilesActive);
                    WeixinServiceMap.putWeixinService(springProfilesActive,weixinService);
                }
                WxMpUser wxMpUser = weixinService.getUserService().userInfo(openId);

                if (wxMpUser != null) {
                    //userInfoMap.put("userWxAvatar", wxMpUser.getHeadImgUrl());
                    userInfoMap.put("userWxAvatar", userInfo.getAvatarUrl());//getUserService()不再返回头像和昵称
                }

            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }


        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(userInfoMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 是否显示开通会员
     * @param userId
     * @return
     */
    @PostMapping(value = "/showVipByUserId", produces = "application/json;charset=UTF-8")
    public RespData showVipByUserId(@RequestHeader("userId") String userId) {
        boolean flag = false;
        int result = userInfoService.showVipByUserId(Integer.valueOf(userId)).intValue();
        if (result > 0) {
            flag = true;
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("flag", flag);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 提示是否开通 VIP
     * 分享了 150 篇文章、非会员且推荐人 3个以下，提示开会员
     * @param userId 用户 ID
     * @return
     */
    @PostMapping(value = "/hintOpenVip", produces = "application/json;charset=UTF-8")
    public RespData hintOpenVip(@RequestHeader("userId") Integer userId) {
        // true-提示开会员 false-不提示
        boolean flag = false;
        Integer vipStatus = userInfoService.getUserVipStatus(userId);
        Integer invitedRegUserCount = userInfoService.getInvitedRegUserCount(userId);
        Integer userSharedArticleCount = userShareArticleInfoService.getUserSharedArticleCount(userId);

        if (userSharedArticleCount >= 150 && vipStatus == 0 && invitedRegUserCount == 0) {
            flag = true;
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("flag", flag);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 检查nickName 是不是 空的
     * @param userId 用户 ID
     * @return
     */
    @PostMapping(value = "/cheakNickName", produces = "application/json;charset=UTF-8")
    public RespData cheakNickName(@RequestHeader("userId") Integer userId) {
        UserInfo userInfo = userInfoService.getUserBaseInfo(userId);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        boolean nickNameIsNull=true;
        if(userInfo!=null && userInfo.getNickName()!=null) {
            nickNameIsNull=false;
        }
        resultMap.put("nickNameIsNull", nickNameIsNull);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 根据个人拥有的佣金级数来返回用户的会员级别(共建获客平台)
     * @param userId 用户 ID
     * @return
     */
    @PostMapping(value = "/vipLevel", produces = "application/json;charset=UTF-8")
    public RespData vipLevel(@RequestHeader("userId") Integer userId) {
        String vipLevel = userInfoService.getUserVipLevel(userId);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("vipLevel", vipLevel);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 用户概览
     * "共建获客平台"专用
     * @param userId
     * @param gzhCode
     * @return
     */
    @PostMapping(value = "/userSummary", produces = "application/json;charset=UTF-8")
    public RespData userSummary(@RequestHeader("userId") Integer userId,
                                @RequestHeader(value = "gzhCode", required = false, defaultValue = "prodgjhkpt") String gzhCode) {
        // 1、我的团队
        int userTeamMemberCount = userInfoService.getUserTeamMemberCount(gzhCode);
        // 2、直接下级
        int subordinateCount = userInfoService.getSubordinateCount(userId);

        int firstLevelCount = 0;// 一级：总监
        int secondeLevelCount = 0;// 二级：经理
        int vipCount = 0;// 会员
        int unVipCount = 0;// 非会员
        List<Integer> userIds = new ArrayList<>();// 总监和经理的 userId 集合

        // 3、总监
        List<Integer> firstLevelUserList = userInfoService.getFirstLevelUser(gzhCode);
        List<Integer> secondLevelUserList = userInfoService.getSecondLevelUser(gzhCode);
        if (CollectionUtils.isNotEmpty(firstLevelUserList)) {
            firstLevelCount = firstLevelUserList.size();
            userIds.addAll(firstLevelUserList);
        }

        if (CollectionUtils.isNotEmpty(secondLevelUserList)) {
            secondeLevelCount = secondLevelUserList.size();
            userIds.addAll(secondLevelUserList);
        }

        if (CollectionUtils.isNotEmpty(userIds)) {
            // 5、会员
            vipCount = userInfoService.getVipUserCount(gzhCode, userIds);
            // 6、非会员
            unVipCount = userInfoService.getUnVipUserCount(gzhCode, userIds);
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("userTeamMemberCount", userTeamMemberCount);
        resultMap.put("subordinateCount", subordinateCount);
        resultMap.put("firstLevelCount", firstLevelCount);
        resultMap.put("secondeLevelCount", secondeLevelCount);
        resultMap.put("vipCount", vipCount);
        resultMap.put("unVipCount", unVipCount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 用户下级列表
     * "共建获客平台"专用
     * @param userId
     * @return
     */
    @PostMapping(value = "/userSubUserList", produces = "application/json;charset=UTF-8")
    public RespData userSubUserList(@RequestHeader("userId") Integer userId, @RequestBody(required = false) LookSubUserReqBean lookSubUserReqBean) {
        Integer finalUserId = userId;
        String nickName = "";

        if (lookSubUserReqBean != null) {
            if (lookSubUserReqBean.getLookUserId() != null && lookSubUserReqBean.getLookUserId().intValue() > 0) {
                finalUserId = lookSubUserReqBean.getLookUserId();
            }
            if (StringUtils.isNotBlank(lookSubUserReqBean.getNickName())) {
                nickName = lookSubUserReqBean.getNickName();
            }
        }
        List<UserInfo> invitedUserInfoList = userInfoService.getUserSubUserList(finalUserId, nickName);
        if (CollectionUtils.isNotEmpty(invitedUserInfoList)) {
            invitedUserInfoList.forEach(info -> {
                Integer invitedRegUserCount = userInfoService.getInvitedRegUserCount(info.getUserId());
                String userVipLevel = userInfoService.getUserVipLevel(info.getUserId());
                info.setSubUserCount(Optional.ofNullable(invitedRegUserCount).orElse(0));
                info.setUserVipLevel(userVipLevel);
            });
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("invitedUserInfoList", invitedUserInfoList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 团队成员数量
     * @return
     */
    @GetMapping(value = "/teamMemberCount", produces = "application/json;charset=UTF-8")
    public RespData teamMemberCount() {
        String gzhCode = "prodgjhkpt";
        // 1、我的团队
        int userTeamMemberCount = userInfoService.getUserTeamMemberCount(gzhCode);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("userTeamMemberCount", userTeamMemberCount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 获取用户的拉黑状态
     * @param userId
     * @return 用户的拉黑状态(0-未拉黑 1-已拉黑)
     */
    @GetMapping(value = "/userBlockState", produces = "application/json;charset=UTF-8")
    public RespData userBlockState(@RequestHeader("userId") String userId) {
        int blockState = userInfoService.getUserBlockState(Integer.valueOf(userId));

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        resultMap.put("blockState", blockState);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 记录用户访问拉黑页面
     * @param userId 用户 ID
     * @param springProfilesActive 公众号标识
     * @return
     */
    @PostMapping(value = "/accessBlockPage", produces = "application/json;charset=UTF-8")
    public RespData accessBlockPage(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive) {
        userInfoService.recordAccessBlockPage(Integer.valueOf(userId), springProfilesActive);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 我的佣金
     * @param userId 用户 ID
     * @return
     */
    @PostMapping(value = "/userPromotionSettle", produces = "application/json;charset=UTF-8")
    public RespData userPromotionSettle(@RequestHeader("userId") String userId) {
        if (StringUtils.isBlank(userId) || !StringUtils.isNumeric(userId)) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer finalUserId = Integer.valueOf(userId);
        double cumulativeIncome = 0D;// 推广总收益
        double userAccountBalance = 0D;// 可提现金额
        int invitedRegUserCount = 0;// 我邀请的人

        // 1、推广总收益
        UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoService.getUserPromotionSettleInfo(finalUserId);
        if (Objects.nonNull(userPromotionSettleInfo)) {
            cumulativeIncome = Optional.ofNullable(userPromotionSettleInfo.getCumulativeIncome()).orElse(0D);
        }

        // 2、可提现金额
        userAccountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(finalUserId)).orElse(0D);

        // 3、我邀请的人
        invitedRegUserCount = Optional.ofNullable(userInfoService.getInvitedRegUserCount(finalUserId)).orElse(0);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("cumulativeIncome", cumulativeIncome);
        resultMap.put("userAccountBalance", userAccountBalance);
        resultMap.put("invitedRegUserCount", invitedRegUserCount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 收益排行榜
     * @param springProfilesActive 公众号标识
     * @return 收益排行榜
     */
    @PostMapping(value = "/incomeRankingList", produces = "application/json;charset=UTF-8")
    public RespData incomeRankingList(@RequestHeader("identifying") String springProfilesActive) {
        List<CombinedIncomeRankingList> userInfoList = userPromotionSettleInfoService.getIncomeRankingList(springProfilesActive);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("userInfoList", userInfoList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 获取用户的会员状态
     * @param userId 用户 ID
     * @return 0-非会员 1-会员
     */
    @GetMapping(value = "/userVipStatus", produces = "application/json;charset=UTF-8")
    public RespData userVipStatus(@RequestHeader("userId") String userId) {
        // 会员状态
        Integer userVipStatus = userInfoService.getUserVipStatus(Integer.valueOf(userId));

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("userVipStatus", userVipStatus);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }
}
